package com.czy.daishusys.ui.bottom;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czy.daishusys.R;
import com.czy.daishusys.adapter.HomeOrderAdapter;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.entity.HomeInfoModel;
import com.czy.daishusys.entity.HomeOrderModel;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseFragment;
import com.czy.daishusys.ui.order.DeliverGoodsEvent;
import com.czy.daishusys.ui.order.OrderDetailActivity;
import com.czy.daishusys.utils.GsonUtils;
import com.czy.daishusys.utils.JsonUtil;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.utils.StatusBarUtil;
import com.czy.daishusys.widget.GradientTextView;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.czy.daishusys.entity.HomeOrderModel.ORDER_EMPTY_TYPE;
import static com.czy.daishusys.entity.HomeOrderModel.ORDER_NORMAL_TYPE;

/**
 * Created by yang on 2017/11/23.
 * 首页
 */

public class HomeFragment extends BaseFragment {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.rv_home_order)
    RecyclerView rvHomeOrder;
    @BindView(R.id.swipe_refresh_home)
    SwipeRefreshLayout mSwipeRefreshLayout;
    HomeOrderAdapter adapter;
    private int page = 1;
    private GradientTextView gtvNewMember;
    private TextView tvTodayTurnover;
    private TextView tvSumTurnover;
    private GradientTextView gtvNewOrder;
    private TextView tvTotalOrder;
    private TextView tvTotalMember;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        StatusBarUtil.setColor(getActivity(), getResources().getColor(R.color.homeToolbarColor));
        toolbarTitle.setText("");
        EventBus.getDefault().register(this);
        List<HomeOrderModel.DataBean.ListBean> data = new ArrayList<>();
        adapter = new HomeOrderAdapter(data);
        adapter.addHeaderView(getHeaderView());
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        });
        adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (adapter.getItemViewType(position)==ORDER_NORMAL_TYPE) {
                    Intent intent = new Intent(mContext, OrderDetailActivity.class);
                    HomeOrderModel.DataBean.ListBean model = (HomeOrderModel.DataBean.ListBean) adapter.getData().get(position);
                    intent.putExtra("orderId", model.getUserOrderId());
                    startActivity(intent);

                }


            }
        });
        rvHomeOrder.setAdapter(adapter);
        rvHomeOrder.setLayoutManager(new LinearLayoutManager(getActivity()));
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.appThemeColor));
        initRefreshLayout();
        mSwipeRefreshLayout.setRefreshing(true);
        refresh();
    }


    private View getHeaderView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.header_home_fragment, (ViewGroup) rvHomeOrder.getParent(), false);
        tvTodayTurnover = (TextView) view.findViewById(R.id.tv_today_turnover);
        tvSumTurnover = (TextView) view.findViewById(R.id.tv_sum_turnover);
        gtvNewOrder = (GradientTextView) view.findViewById(R.id.gtv_new_order);
        tvTotalOrder = (TextView) view.findViewById(R.id.tv_total_order);
        gtvNewMember = (GradientTextView) view.findViewById(R.id.gtv_new_member);
        tvTotalMember = (TextView) view.findViewById(R.id.tv_total_member);
        return view;
    }

    @Override
    protected void updateViews() {
        StatusBarUtil.setColor(getActivity(), getResources().getColor(R.color.homeToolbarColor));
    }

    private void initRefreshLayout() {
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    private void refresh() {
        page = 1;
        adapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        getHomeData();
        getOrderData();

    }

    private void loadMore() {
        page++;
        getOrderData();
    }

    private void getHomeData() {
        HttpParams params = new HttpParams();
        params.put("session", UserHelper.getInstance().getSessionInfoModel(mContext).getSession());
        params.put("pid",UserHelper.getInstance().getDevicePid());
        EasyHttp.post(Constants.SYS_HOME).params(params).execute(new SimpleCallBack<String>
                () {
            @Override
            public void onError(ApiException e) {

            }

            @Override
            public void onSuccess(String s) {
                boolean flag = JsonUtil.getJsonValuesBoolean(s, "flag");
                if (flag) {
                    HomeInfoModel.DataBean model = GsonUtils.fromJson(s, HomeInfoModel.class).getData();
                    tvTodayTurnover.setText(String.format("%.2f", model.getOrderPrice()));
                    tvSumTurnover.setText("订单总额: " + String.format("%.2f", model.getSumOrderPrice()));
                    gtvNewOrder.setText(model.getOrderNum() + "");
                    tvTotalOrder.setText("总单数: " + model.getSumOrderNum());
                    gtvNewMember.setText(model.getRegisterUserCountToday() + "");
                    tvTotalMember.setText("总会员数: " + model.getSumRegisterUserCountToday());
                }else{
                    MyLog.d("Home","onSuccess error");
                }
            }
        });

    }

    private void getOrderData() {
        HttpParams params = new HttpParams();
        params.put("session", UserHelper.getInstance().getSessionInfoModel(mContext).getSession());
        params.put("page", page + "");
        params.put("pageSize", "10");
        params.put("status", "waitDelivery");
        params.put("pid",UserHelper.getInstance().getDevicePid());
        MyLog.d("RAVEN","pid = " + UserHelper.getInstance().getDevicePid());
        EasyHttp.post(Constants.SYS_ORDER_LIST).params(params).execute(new SimpleCallBack<String>
                () {
            @Override
            public void onError(ApiException e) {
                if (page == 1) {
                    adapter.setEnableLoadMore(true);
                    mSwipeRefreshLayout.setRefreshing(false);
                } else {
                    adapter.loadMoreFail();
                }

                PhoneUtils.ShowToastMessage(mContext, e.getMessage());
            }

            @Override
            public void onSuccess(String s) {
                if (page == 1) {
                    adapter.setEnableLoadMore(true);
                    mSwipeRefreshLayout.setRefreshing(false);
                }
                String exp = JsonUtil.getJsonValuesString(s, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(s, "flag");
                if (flag) {
                    HomeOrderModel model = GsonUtils.fromJson(s, HomeOrderModel.class);
                    List<HomeOrderModel.DataBean.ListBean> list = model.getData().getList();
                    if (page == 1) {
                        setOrderData(true, list);
                    } else {
                        setOrderData(false, list);
                    }
                } else {
                    adapter.loadMoreFail();
                    PhoneUtils.ShowToastMessage(mContext, exp);
                }


                //adapter.removeAllHeaderView();
            }
        });

    }


    private void setOrderData(boolean isRefresh, List<HomeOrderModel.DataBean.ListBean> data) {
        for (int i = 0; i < data.size(); i++) {
            data.get(i).setItemType(HomeOrderModel.ORDER_NORMAL_TYPE);
        }
        if (isRefresh) {
            if (data.size() == 0) {
                HomeOrderModel.DataBean.ListBean model = new HomeOrderModel.DataBean.ListBean();
                model.setItemType(ORDER_EMPTY_TYPE);
                data.add(model);
            }
        }
        int size = data.size();
        if (isRefresh) {
            adapter.setNewData(data);
        } else {
            if (size > 0) {
                adapter.addData(data);
            }
        }
        if (size < 10) {

            adapter.loadMoreEnd(isRefresh);

        } else {
            adapter.loadMoreComplete();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        setStatusBar(getResources().getColor(R.color.homeToolbarColor));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEventMainThread(DeliverGoodsEvent event) {
        if ("refresh".equals(event.getmMsg())) {
            refresh();
        }
    }

}
